#include "mycalc.h"

extern "C" {

	void* ZQDB_CALC_DATA_Open(HZQDB code, PERIODTYPE cycle, size_t cycleex, size_t flags)
	{
		return new zqdb::CalcData(code, cycle, cycleex, flags);
	}

	void ZQDB_CALC_DATA_Close(void* data)
	{
		delete (zqdb::CalcData*)data;
	}

	void* ZQDB_CALC_DATA_GetFieldValue(void* data, MDB_FIELD* field)
	{
		return ((zqdb::CalcData*)data)->GetFieldValue(*field);
	}

	size_t ZQDB_CALC_DATA_GetDataMaxCount(void* data)
	{
		return ((zqdb::CalcData*)data)->GetDataMaxCount();
	}

	size_t ZQDB_CALC_DATA_GetDataCount(void* data)
	{
		return ((zqdb::CalcData*)data)->GetDataCount();
	}

	void* ZQDB_CALC_DATA_GetDataValue(void* data, MDB_FIELD* field)
	{
		return ((zqdb::CalcData*)data)->GetDataValue(*field);
	}

}

namespace zqdb {

	CalcData::CalcData(HZQDB code, PERIODTYPE cycle, size_t cycleex, size_t flags)
		: Handle(ZQDB_HANDLE_TYPE_UNKNOWN, flags)
		, CALCDATA{ code, cycle, cycleex }
	{
		/*if (!ZQDBIsSubscribeMarketDataAll(code)) {
			if (HasFlags(CALC_DATA_FLAG_SYNC_DATA)) {
				ZQDBSyncData(code, cycle, cycleex, false);
			}
			if (HasFlags(CALC_DATA_FLAG_ASYNC_DATA)) {
				ZQDBSyncData(code, cycle, cycleex, true);
			}
		}*/
	}

	CalcData::~CalcData()
	{
	}

	void* CalcData::GetFieldValue(MDB_FIELD& field)
	{
		if (MDB_STATUS_OK == ZQDBNormalizeField(h, &field, 1)) {
			return ZQDBGetValue(h);
		}
		return nullptr;
	}

	size_t CalcData::GetDataMaxCount()
	{
		return ZQDBGetDataMaxCount(h, cycle, cycleex);
		if (data_.empty()) {
			return 0;
		}
		return data_.begin()->second.size() / data_.begin()->first.size;
	}

	size_t CalcData::GetDataCount()
	{
		return ZQDBGetDataCount(h, cycle, cycleex, nullptr);
		if (data_.empty()) {
			return 0;
		}
		return count_;
	}

	void* CalcData::GetDataValue(MDB_FIELD& field)
	{
		return ZQDBGetDataValueEx(h, cycle, &field);
		auto it = data_.find(field);
		if (it != data_.end()) {
			if (!MDBFieldIsNormalized(field)) {
				field = it->first;
				field.offset = 0;
			}
			ASSERT(field.size == it->first.size);
			return it->second.data() + it->first.size * offset_;
		}
		return nullptr;
	}

}
